/*

 * Licensed to the Apache Software Foundation (ASF) under one

 * or more contributor license agreements.  See the NOTICE file

 * distributed with this work for additional information

 * regarding copyright ownership.  The ASF licenses this file

 * to you under the Apache License, Version 2.0 (the

 * "License"); you may not use this file except in compliance

 * with the License.  You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package com.bff.gaia.unified.sdk.nexmark;



import com.bff.gaia.unified.sdk.metrics.Counter;

import com.bff.gaia.unified.sdk.metrics.Distribution;

import com.bff.gaia.unified.sdk.metrics.Metrics;

import com.bff.gaia.unified.sdk.nexmark.model.KnownSize;

import com.bff.gaia.unified.sdk.transforms.DoFn;

import com.bff.gaia.unified.sdk.transforms.PTransform;

import com.bff.gaia.unified.sdk.transforms.ParDo;

import com.bff.gaia.unified.sdk.values.PCollection;



import java.io.Serializable;



/**

 * A monitor of elements with support for later retrieving their metrics.

 *

 * @param <T> Type of element we are monitoring.

 */

public class Monitor<T extends KnownSize> implements Serializable {

  private class MonitorDoFn extends DoFn<T, T> {

    final Counter elementCounter = Metrics.counter(name, prefix + ".elements");

    final Counter bytesCounter = Metrics.counter(name, prefix + ".bytes");

    final Distribution startTime = Metrics.distribution(name, prefix + ".startTime");

    final Distribution endTime = Metrics.distribution(name, prefix + ".endTime");

    final Distribution startTimestamp = Metrics.distribution(name, prefix + ".startTimestamp");

    final Distribution endTimestamp = Metrics.distribution(name, prefix + ".endTimestamp");



    @ProcessElement

    public void processElement(ProcessContext c) {

      elementCounter.inc();

      bytesCounter.inc(c.element().sizeInBytes());

      long now = System.currentTimeMillis();

      startTime.update(now);

      endTime.update(now);

      startTimestamp.update(c.timestamp().getMillis());

      endTimestamp.update(c.timestamp().getMillis());

      c.output(c.element());

    }

  }



  public final String name;

  public final String prefix;

  private final MonitorDoFn doFn;

  private final PTransform<PCollection<? extends T>, PCollection<T>> transform;



  public Monitor(String name, String prefix) {

    this.name = name;

    this.prefix = prefix;

    doFn = new MonitorDoFn();

    transform = ParDo.of(doFn);

  }



  public PTransform<PCollection<? extends T>, PCollection<T>> getTransform() {

    return transform;

  }

}